import requests
from src.constants import huawei_constants as constants
import re
from openpyxl import Workbook


def get_card_list(queue):
    """
    获取卡片列表
    通过API请求获取所有已批准的卡片信息
    """
    card_list = []
    # 请求参数
    data = {
        "cardChannel": "cn",  # 卡片频道
        "serviceId": "43",  # 服务ID
        "cardId": "",  # 卡片ID
        "size": 10,  # 每页条数
        "page": 1,  # 页码
        "type": "all",  # 类型
        "cardLevel": 1,  # 卡片等级
        "cardLearningPhase": ""  # 学习阶段
    }

    # 发送首次请求获取总页数
    response = requests.post(constants.GET_APPROVED_CARD_LIST_BY_CATEGORY, data=data, headers=constants.headers)
    max_page = response.json()["pageInfo"]["totalRecords"] // 10 + 1

    # 分页获取所有卡片信息
    for page_num in range(1, max_page + 1):
        data["page"] = page_num
        response = requests.post(constants.GET_APPROVED_CARD_LIST_BY_CATEGORY, data=data, headers=constants.headers)
        cards = response.json()["value"]

        # 提取每张卡片的基本信息
        for card in cards:
            card_info = {
                "cardName": card['cardName'],  # 卡片名称
                "cardDocFileName": card['cardDocFileName']  # 卡片文档文件名
            }
            card_list.append(card_info)
            queue.put(f'获取{card_info["cardName"]}成功')
    return card_list


def get_card_document(card_info, queue):
    """
    获取卡片详细文档内容
    :param queue:
    :param card_info: 卡片基本信息
    :return: 包含章节内容的完整卡片信息
    """
    # 初始化结果结构
    result = {'cardDocFileName': card_info["cardDocFileName"], 'chapters': [], 'cardName': card_info["cardName"]}

    # 请求参数
    data = {
        'cardDocFileName': card_info["cardDocFileName"],  # 文档文件名
        'cardChannel': "cn"  # 频道
    }

    # 发送请求获取卡片详细信息
    response = requests.post(constants.QUERY_CARD_INFO, data=data, headers=constants.headers)
    queue.put(f"{card_info['cardName']}")

    # 解析章节内容
    content = response.json()['value']['chapterInfoDOList']
    for chapter in content:
        queue.put(f"{chapter['chapterName']}")
        print(f"{chapter['content']}")
        content = chapter['content']
        for link in parse_content(content, queue):
            result['chapters'].append(
                {'chapterName': chapter['chapterName'], 'link_text': link[0], 'link_url': link[1]})
        # 添加章节信息到结果中
    return result


def parse_content(content, queue):
    """
    解析卡片内容
    :param queue:
    :param content: 卡片内容
    :return: 解析后的内容
    """
    links = []
    # 使用正则表达式匹配链接
    pattern = r'<a\s+href\s*=\s*\\"([^"]+)\\"[^>]*>(.*?)</a>'
    matches = re.findall(pattern, content)
    for match in matches:
        link_url, link_text = match
        queue.put(f"获取链接成功  {link_text}： {link_url}")
        links.append((link_text, link_url))
    return links


def write_to_excel(result):
    wb = Workbook()
    ws = wb.active
    ws.append(['卡片名称', "卡片地址", "章节名称", '链接信息', '超链接地址'])
    for card in result:
        print(card)
        card_name = card['cardName']
        card_url = "https://developer.huawei.com/consumer/cn/codelabsPortal/carddetails/" + card['cardDocFileName']
        for chapter in card['chapters']:
            chapter_name = chapter['chapterName']
            link_text = chapter['link_text']
            link_url = chapter['link_url']
            ws.append([card_name, card_url, chapter_name, link_text, link_url])
    wb.save(f"超链接_CodeLabs.xlsx")


def main(queue):
    """
    主函数
    """
    result = []
    # 获取卡片列表
    card_list = get_card_list(queue)

    # 获取卡片详细文档内容
    for card_info in card_list:
        card_document = get_card_document(card_info, queue)
        result.append(card_document)

    write_to_excel(result)


if __name__ == '__main__':
    pass
